package pers.zb.cloud.gateway.handler;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * API服务异常处理器
 */
@Configuration
public class ZuulFallbackHandler implements FallbackProvider {
    private String route = null;

    //通用的错误信息
    private static final String FAILBACK_RESPONSE_BODY = "{\"timestamp\":\"%s\",\"status\":%s,\"message\":\"%s\",\"route\":\"%s\"}";

    @Override
    public String getRoute() {
        return route;
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {}

            /**
             * API服务不可用的情况下，返回错误信息
             */
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(String.format(FAILBACK_RESPONSE_BODY,DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"),500,"系统服务出现了问题，请稍后重试",route).getBytes());
            }

            /**
             * 设置返回的数据类型 - json
             */
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
                headers.setContentType(mt);
                return headers;
            }
        };
    }

    /**
     * 设置API服务的service-id，具体处理逻辑在 RouteFallbackHandlerConfig.java 中的 initRoute 方法
     * @param route
     */
    public void setRoute(String route) {
        this.route = route;
    }
}
